define(['underscore','backbone','jquery','collections/widgets','views/image','views/purehtml','views/richtext','models/image','models/purehtml','models/richtext','fancybox','json2','jquery.cookie'], function(_,Backbone,$,Widgets,ViewImage,ViewPureHTML,ViewRichText,Image,PureHTML,RichText){
    var PageView = Backbone.View.extend({
        el : $('#box-content'),
        events : {
            'click #list-container a' : 'setCurrentPage',
            'click .sortable > a > .collapse' : 'toggle',
            'change #workflow_id' : 'setCurrentWorkflow'
        },
        initialize : function(){
            this.widget_url = $('.widget_url').attr('href');

            //expand, collapse pages
            this.toggle_data = $.cookie('master_content') || {};
            if (typeof this.toggle_data === 'string')
            {
                var tmp = {};
                JSON.parse(this.toggle_data, function(key,value){
                    tmp[key] = value;
                    key = key.replace('_','-');
                    if (value == 1)
                    {
                        $('#'+key+' > a > .collapse').removeClass('expand');
                        $('#'+key+' > ul').show();
                    }
                });
                this.toggle_data = tmp;
            }
        },
        toggle : function(event){
            var item = $(event.target),
                _this = this,
                id = $(event.target).closest('.sortable').attr('id');
            if (item.hasClass('expand'))
            {
                $.each($(event.target).closest('.sortable').siblings(), function(){
                    $(this).find(' > a > .collapse').addClass('expand')
                        .parent().next('ul').hide();
                    var _id = $(this).attr('id');
                    _this.toggle_data[_id] = 0;
                });
                item.parent().next('ul').show();
                this.toggle_data[id] = 1;
            }
            else
            {
                item.parent().next('ul').hide();
                this.toggle_data[id] = 0;
            }
            $.cookie('master_content', JSON.stringify(this.toggle_data));
            item.toggleClass('expand');
            //scroll to expand element
            var wst = $(window).scrollTop(), ist = item.closest('.sortable').offset().top;
            if (wst > ist)
            {
                $('html,body').animate({ scrollTop: ist }, { duration: 'slow', easing: 'swing'});
            }
            return false;
        },
        setCurrentPage : function(event) {
            if ($(event.target).closest('li').hasClass('current')) return false;
            $('#list-container .current').removeClass('current');
            $(event.target).closest('li').addClass('current');
            this.renderContent();
            this.$('#workflow_id').focus();
            return false;
        },
        setCurrentWorkflow : function(event) {
            this.renderContent();
            return false;
        },
        renderContent : function() {
            this.workflow_id = $('#workflow_id').val();
            this.page_id = $('#list-container .current').attr('id').replace('items-','');
            //load page widgets
            if (this.workflow_id && this.page_id)
            {
                this.$(".widgets").html('');
                this.widgets = new Widgets;
                this.widgets.bind('reset', this.addAll, this);
                this.widgets.url = this.widget_url;
                var _this = this;
                this.widgets.fetch({data:{page_id:this.page_id,workflow_id:this.workflow_id}});
            }
        },
        addOne: function(widget) {
            switch (widget.get('type'))
            {
                case 'image':
                    var view = new ViewImage({model: widget});
                    this.$(".widgets").append(view.render().el);
                    break;
                case 'purehtml':
                    var view = new ViewPureHTML({model: widget});
                    this.$(".widgets").append(view.render().el);
                    view.edit();
                    break;
                case 'richtext':
                    var view = new ViewRichText({model: widget});
                    this.$(".widgets").append(view.render().el);
                    view.edit();
                    break;
            }
        },
        addAll : function()
        {
            if (this.widgets.active_workflow !== false && (this.active_workflow_old == undefined || this.active_workflow_old != this.widgets.active_workflow))
            {
                this.active_workflow_old = this.widgets.active_workflow;
                $.fancybox({
                    type: 'iframe',
                    href: this.widgets.active_workflow,
                    width: '100%',
                    height: '100%',
                    showCloseButton: true,
                    hideOnOverlayClick: false,
                    autoScale: false,
                    titleShow: false,
                    onStart: function(){$('body').css({'overflow':'hidden'});},
                    onClosed: $.proxy(function(){
                        $('body').css({'overflow':'auto'});
                        //update content
                        this.renderContent();
                    },this)
                });
            }
            else if (this.widgets.size())
            {
                this.widgets.each(this.addOne);
            }
            else
            {
                this.$(".widgets").html('<p class="empty-content">There is no text or image content on this page</p>');
            }
        }
    });
    return PageView;
});